<template>
  <view class="app-container">
    <view class="flex-1" style="overflow-y: auto" id="scrollWrapper">
      <scroll-view
        scroll-y
        :style="{ height: scrollHeight + 'px' }"
        @scrolltolower="handleScrolltolower"
        refresher-enabled
        :refresherTriggered="refresherTriggered"
        @refresherrefresh="handleRefresherrefresh"
      >
        <view class="p-20">
          <view v-for="(record, index) in list" :key="index" class="my-card mb-20">
            <u-text :text="record.order.name" size="18" bold></u-text>
            <view :style="{ fontSize: '50rpx', color: record.type == 'get' ? 'green' : 'red', fontWeight: 'bold' }">
              <view>
                {{ typeMap[record.type] }}
                {{ Number(record.amount).toFixed(2) }}
              </view>
            </view>
            <u-text :text="record.create_date"></u-text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
  import { onReady, onShow } from "@dcloudio/uni-app";
  import { useWalletStore } from "../../store/wallet";
  import { reactive, ref } from "vue";

  const walletStore = useWalletStore();

  const scrollHeight = ref(400);

  const params = reactive({
    page: 1,
    size: 20,
  });

  const refresherTriggered = ref(false);

  const list = ref([]);

  const totalPage = ref(0);

  const typeMap = {
    get: "+",
    withdraw: "-",
  };

  function handleScrolltolower(e) {
    if (totalPage < params.page) {
      params.page += 1;
      getList();
    }
  }

  async function getList() {
    const res = await walletStore.fetchWalletRecord(params);
    if (res) {
      totalPage.value = res.total_page;
      list.value = res.records;
    }
  }

  async function handleRefresherrefresh() {
    refresherTriggered.value = true;
    params.page = 1;
    await getList();
    refresherTriggered.value = false;
    uni.$u.toast("刷新成功");
  }

  onShow(() => {
    getList();
  });

  onReady(() => {
    const wrapper = uni.createSelectorQuery().select("#scrollWrapper");
    wrapper.boundingClientRect().exec((e) => {
      if (e[0]) {
        scrollHeight.value = e[0].height;
      }
    });
  });
</script>

<style lang="scss" scoped></style>
